/**
 * @filename:SysUserServiceImpl 2025-05-09
 * @project starhub-schema  V1.0
 */
package com.starhub.engine.sys.user.service.impl;

import com.starhub.api.sys.user.dto.PasswordDto;
import com.starhub.api.sys.user.dto.SysUserDto;
import com.starhub.common.bean.BrowserBean;
import com.starhub.common.exception.AppException;
import com.starhub.common.sys.user.LoginUser;
import com.starhub.engine.generator.genid.IdGenerator;
import com.starhub.engine.sys.user.dao.SysUserDao;
import com.starhub.engine.sys.user.entity.SysUser;
import com.starhub.engine.sys.user.service.SysUserService;
import com.starhub.utils.ColorUtil;
import com.starhub.utils.DateUtil;
import com.starhub.utils.Util;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**   
 * @Description:(用户设置服务实现)
 *
 * @version: V1.0
 * @author: luosw
 * 
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public SysUser selectUserByUserName(String username) {

        SysUser record = new SysUser();
        record.setDeleteType(0);
        record.setUsername(username);
        record.setStatus("active"); //启用账户才允许登录
        List<SysUser> userList = sysUserDao.selectByPrimaryKeySelective(record);
        if(CollectionUtils.isNotEmpty(userList)){
            return userList.get(0);
        }else{
            return null;
        }
    }


    /**
    * 新增
    * @param user
    * @param sysUser
    * @return
    */
    public Long add(LoginUser user, SysUser sysUser){

        SysUser record = new SysUser();
        record.setUsername(sysUser.getUsername());
        List<SysUser> sysUserList = sysUserDao.selectByPrimaryKeySelective(record);
        if(CollectionUtils.isNotEmpty(sysUserList)){
            throw new AppException(500,"当前用户名重复，请重新输入");
        }
        Long id = IdGenerator.generateId();
        sysUser.setStatus(sysUser.getStatus().equals("true") ? "active" : "inactive");
        //数据封装，默认值添加
        sysUser.setId(id);
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUser.setDeleteType(0);
        if(StringUtils.isEmpty(sysUser.getPassword())){
            sysUser.setPassword("123456");
        }
        String rawPassword = sysUser.getPassword(); //默认密码  $2a$10$dXJwZ6Lr3rF8V7DnJt4NXuYB9QZ6Q1cXvzLd1sS5WkKjHmMlN2/G
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        sysUser.setPassword(encodedPassword);
        sysUserDao.insertSelective(sysUser);
        return id;
    }

    /**
    * 更新
    * @param user
    * @param sysUser
    * @return
    */
    public SysUser update(LoginUser user, SysUser sysUser){
        sysUser.setUpdateTime(new Date());
        sysUser.setStatus(sysUser.getStatus().equals("true") ? "active" : "inactive");
        //不允许更新的属性设置为null
        sysUserDao.updateByPrimaryKeySelective(sysUser);
        return sysUser;
    }

    /**
     * 更新
     * @param user
     * @return
     */
    public SysUser updateLastLogin(LoginUser user){

        SysUser sysUser = new SysUser();
        sysUser.setId(user.getUser().getId());
        sysUser.setLastLogin(DateUtil.getCurrentDateTimeString()); //更新最后一次登录时间
        //不允许更新的属性设置为null
        sysUserDao.updateByPrimaryKeySelective(sysUser);
        return sysUser;
    }

    /**
    * 基本信息获取
    * @param user
    * @param id
    * @return
    */
    public SysUserDto getInfo(LoginUser user, Long id){

        SysUser sysUser = sysUserDao.selectByPrimaryKey(id);
        SysUserDto sysUserDto = new SysUserDto();
        BeanUtils.copyProperties(sysUser,sysUserDto);//剔除隐私属性
        return sysUserDto;
    }

    /**
    * (批量)删除，同时支持单条或者批量,此方法为逻辑删除
    * @param user
    * @param ids
    */
    public void deleteByType(LoginUser user, String ids,int deleteType){

        //数组转换
        List<Long> idList = Arrays.stream(ids.split(","))
            .map((id) -> Long.parseLong(id))
            .collect(Collectors.toList());
            //删除状态，目前只有1的逻辑
        sysUserDao.deleteSysUserByType(idList, deleteType);
    }

    /**
    * 根据id删除，此方法为真实删除
    * @param user
    * @param ids
    */
    public void deleteRecord(LoginUser user, String ids){

        //数组转换
        List<Long> idList = Arrays.stream(ids.split(","))
            .map((id) -> Long.parseLong(id))
            .collect(Collectors.toList());
        sysUserDao.deleteSysUserRecord(idList);
    }

    /**
    * 列表查询
    * @param user
    * @param params
    */
    public List<SysUser> getList(LoginUser user,  Map<String , Object>  params){

        List<SysUser> sysUserList =  new ArrayList<SysUser>();
        int pageSize = 10;
        int current = 1;
        SysUser record = new SysUser();
        record.setDeleteType(0);
        record.setStatus("active");
        sysUserList = sysUserDao.selectByPrimaryKeySelective(record);
        return sysUserList;
    }

    @Override
    public SysUser updatePassword(LoginUser user, PasswordDto passwordDto) {

        SysUser sysUser = sysUserDao.selectByPrimaryKey(user.getUser().getId());
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String rawPassword = passwordDto.getOldPassword();
        boolean matches = encoder.matches(rawPassword, sysUser.getPassword());//二次判断旧密码与实际密码是否一致
        if(!matches){
            throw new AppException(403,"当前密码错误，请重新输入");
        }
        String encodedPassword = encoder.encode(passwordDto.getPassword()); //入库密码需要加密
        passwordDto.setPassword(encodedPassword);
        passwordDto.setUpdateTime(new Date());
        SysUser updateUser = new SysUser();
        BeanUtils.copyProperties(passwordDto,updateUser);
        updateUser.setId(user.getUser().getId());
        sysUserDao.updateByPrimaryKeySelective(updateUser);
        return sysUser;
    }

    @Override
    public void batchUpdatePwd(LoginUser user, PasswordDto passwordDto) {

        List<String> ids = passwordDto.getIds();
        if(CollectionUtils.isNotEmpty(ids)){
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodedPassword = encoder.encode(passwordDto.getPassword()); //入库密码需要加密
            for(String id :ids){
                passwordDto.setPassword(encodedPassword);
                passwordDto.setUpdateTime(new Date());
                SysUser updateUser = new SysUser();
                BeanUtils.copyProperties(passwordDto,updateUser);
                updateUser.setId(Util.getLongValue(id));
                sysUserDao.updateByPrimaryKeySelective(updateUser);
            }
        }
    }

    @Override
    public Integer resetPassword(LoginUser user, PasswordDto passwordDto) {

        List<String> ids = passwordDto.getIds();
        if(CollectionUtils.isNotEmpty(ids)){
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            if(StringUtils.isEmpty(passwordDto.getPassword())){
                passwordDto.setPassword("123456");
            }
            String encodedPassword = encoder.encode(passwordDto.getPassword()); //入库密码需要加密
            for(String id : ids){
                passwordDto.setPassword(encodedPassword);
                passwordDto.setUpdateTime(new Date());
                SysUser updateUser = new SysUser();
                BeanUtils.copyProperties(passwordDto,updateUser);
                updateUser.setId(Util.getLongValue(id));
                return sysUserDao.updateByPrimaryKeySelective(updateUser);
            }
        }
        return 0;
    }

    @Override
    public int countValidUsers() {
        SysUser record = new SysUser();
        record.setDeleteType(0);
        record.setStatus("active");
        // 查询所有有效用户
        List<SysUser> userList = sysUserDao.selectByPrimaryKeySelective(record);
        return userList != null ? userList.size() : 0;
    }

    @Override
    public SysUserDto updateUser(LoginUser user, SysUserDto sysUserDto) {

        SysUser record = new SysUser();
        record.setUsername(sysUserDto.getUsername());
        List<SysUser> sysUserList = sysUserDao.selectByPrimaryKeySelective(record);
        if(CollectionUtils.isNotEmpty(sysUserList)){
            List<Long> userIds = sysUserList.stream().map(SysUser::getId).collect(Collectors.toList());
            if(!(userIds.size()==1 && userIds.contains(user.getUser().getId()))){
                throw new AppException(500,"当前用户名重复，请重新输入");
            }
        }
        sysUserDto.setId(user.getUser().getId());
        sysUserDto.setUpdateTime(new Date());

        SysUser updateUser = new SysUser();
        BeanUtils.copyProperties(sysUserDto,updateUser);
        sysUserDao.updateByPrimaryKeySelective(updateUser);
        return sysUserDto;
    }

    @Override
    public Map<String, BrowserBean> getActiveUser(LoginUser user, Map<String, Object> params) {

        Map<String, BrowserBean> result = new HashMap<>();
        SysUser record = new SysUser();
        record.setDeleteType(0);
        record.setStatus("active");
        // 查询所有有效用户
        List<SysUser> userList = sysUserDao.selectByPrimaryKeySelective(record);
        List<String> dColors = ColorUtil.dColors;
        int i =0 ;
        if(CollectionUtils.isNotEmpty(userList)){
            for(SysUser sysUser : userList){
                int co = i % dColors.size();
                i++;
                String color = dColors.get(co);
                BrowserBean bean = new BrowserBean(Util.null2String(sysUser.getId()) ,sysUser.getName(),color);
                result.put(Util.null2String(sysUser.getId()),bean);
            }

        }
        return result;
    }

}